
// 本地化消息管理系统
const i18nMessageCache = {
    zh_CN: null,
    en: null
};

// 加载指定语言的消息
async function loadMessages(locale) {
    if (i18nMessageCache[locale]) {
        return i18nMessageCache[locale];
    }

    try {
        const response = await fetch(`_locales/${locale}/messages.json`);
        const messages = await response.json();
        i18nMessageCache[locale] = messages;
        return messages;
    } catch (error) {
        console.error('加载语言消息失败:', error);
        return null;
    }
}

// 获取指定语言的消息
async function getMessageFromLocale(key, locale, substitutions = null) {
    const messages = await loadMessages(locale);
    if (!messages || !messages[key]) {
        return key;
    }

    let message = messages[key].message;

    // 处理替换参数
    if (substitutions && messages[key].placeholders) {
        Object.entries(messages[key].placeholders).forEach(([placeholder, config]) => {
            const index = parseInt(config.content.replace('$', '')) - 1;
            if (substitutions[index]) {
                message = message.replace(`$${placeholder.toUpperCase()}$`, substitutions[index]);
            }
        });
    }

    return message;
}

// 更新获取消息的函数
async function getMessage(key, substitutions = null) {
    const { language = 'zh_CN' } = await chrome.storage.sync.get('language');
    return await getMessageFromLocale(key, language, substitutions);
}

// 更新页面上的所有i18n文本
async function updateI18nText() {
    const elements = document.querySelectorAll('[data-i18n]');
    for (const element of elements) {
        const key = element.getAttribute('data-i18n');
        const text = await getMessage(key);
        if (text) {
            if (element.tagName.toLowerCase() === 'input' && element.type === 'text') {
                element.placeholder = text;
            } else {
                element.textContent = text;
            }
        }
    }

    // 更新带title属性的元素
    const titleElements = document.querySelectorAll('[data-i18n-title]');
    for (const element of titleElements) {
        const key = element.getAttribute('data-i18n-title');
        const text = await getMessage(key);
        if (text) {
            element.title = text;
        }
    }
}

// 加载语言设置
async function loadLanguageSettings() {
    try {
        const { language = 'zh_CN' } = await chrome.storage.sync.get('language');
        document.getElementById('languageSelect').value = language;
    } catch (error) {
        console.error('加载语言设置失败:', error);
    }
}

// 保存语言设置
async function saveLanguageSettings(newLanguage) {
    try {
        await chrome.storage.sync.set({ language: newLanguage });
        
        // 通知所有标签页更新语言
        const tabs = await chrome.tabs.query({});
        for (const tab of tabs) {
            try {
                await chrome.tabs.sendMessage(tab.id, { 
                    action: 'updateLanguage',
                    language: newLanguage
                });
            } catch (error) {
                // 忽略未加载内容脚本的标签页错误
            }
        }

        // 通知后台脚本
        chrome.runtime.sendMessage({ 
            action: 'updateLanguage',
            language: newLanguage 
        });

        // 显示成功提示
        showStatus(await getMessage('settingsSaved'), 'success');
        
        // 重新加载页面以应用新语言
        setTimeout(() => {
            window.location.reload();
        }, 500);
    } catch (error) {
        console.error('保存语言设置失败:', error);
        showStatus(await getMessage('settingsSaveError'), 'error');
    }
}

// 保存网站列表到 storage
function saveOptions() {
    const urlItems = document.querySelectorAll('#urlList .flex');
    const urls = [];
    const disabledUrls = [];
    
    urlItems.forEach(item => {
        const input = item.querySelector('input[type="text"]');
        const url = input.value.trim();
        if (url !== '') {
            if (item.classList.contains('disabled')) {
                disabledUrls.push(url);
            } else {
                urls.push(url);
            }
        }
    });
    
    console.log('准备保存的URL列表:', { 
        enabledUrls: urls, 
        disabledUrls: disabledUrls 
    });
    
    const enableLogging = document.getElementById('enableLogging').checked;
    
    const status = document.getElementById('status');
    status.classList.remove('hidden');
    status.style.transform = 'translateY(100%)';
    status.style.opacity = '0';
    
    // 使用明确的对象结构保存数据
    const dataToSave = {
        enabledUrls: urls,
        disabledUrls: disabledUrls,
        enableLogging: enableLogging
    };
    
    console.log('即将保存到storage的完整数据:', dataToSave);
    
    chrome.storage.sync.set(dataToSave, () => {
        if (chrome.runtime.lastError) {
            console.error('保存失败:', chrome.runtime.lastError);
            showStatus('保存失败！', 'error');
        } else {
            console.log('保存成功!');
            showStatus('设置已保存！', 'success');
            
            // 立即验证保存的数据
            chrome.storage.sync.get(['enabledUrls', 'disabledUrls'], (result) => {
                console.log('验证刚保存的数据:', result);
                if (!result.enabledUrls || !Array.isArray(result.enabledUrls)) {
                    console.error('警告：enabledUrls数据不符合预期格式');
                }
            });
        }
    });
}

// 从 storage 加载网站列表
function loadOptions() {
    chrome.storage.sync.get({
        enabledUrls: [],
        disabledUrls: [],
        enableLogging: true  // 默认启用日志
    }, (items) => {
        const urlList = document.getElementById('urlList');
        if (!urlList) {
            console.error('无法找到 urlList 元素');
            return;
        }
        
        // 设置日志选项
        document.getElementById('enableLogging').checked = items.enableLogging;
        
        urlList.innerHTML = '';
        
        // 加载已启用的 URL
        if (Array.isArray(items.enabledUrls)) {
            items.enabledUrls.forEach((url, index) => {
                if (typeof url === 'string') {
                    setTimeout(() => addUrlInput(url, false), index * 100);
                }
            });
        }

        // 加载已禁用的 URL
        if (Array.isArray(items.disabledUrls)) {
            items.disabledUrls.forEach((url, index) => {
                if (typeof url === 'string') {
                    setTimeout(() => addUrlInput(url, true), (items.enabledUrls.length + index) * 100);
                }
            });
        }

        // 如果没有任何 URL，添加一个空的输入框
        if (!items.enabledUrls.length && !items.disabledUrls.length) {
            addUrlInput('');
        }
    });
}

// 添加新的 URL 输入框
function addUrlInput(value = '', isDisabled = false) {
    const urlList = document.getElementById('urlList');
    if (!urlList) {
        console.error('无法找到 urlList 元素');
        return;
    }

    const urlItem = document.createElement('div');
    urlItem.className = `flex items-center space-x-4 opacity-0 transform translate-y-2 mb-4 ${isDisabled ? 'disabled' : ''}`;
    
    const input = document.createElement('input');
    input.type = 'text';
    input.className = 'flex-1 px-4 py-2 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all';
    input.placeholder = '输入网页路径，例如：/video/';
    input.value = value;
    
    const toggleButton = document.createElement('button');
    toggleButton.className = `px-6 py-3 ml-4 ${isDisabled ? 'bg-green-500' : 'bg-yellow-500'} text-white rounded-lg transition-colors flex-shrink-0`;
    toggleButton.innerHTML = isDisabled ? '启用' : '禁用';
    
    toggleButton.onclick = async () => {
        const newIsDisabled = urlItem.classList.contains('disabled') ? false : true;
        urlItem.classList.toggle('disabled');
        toggleButton.innerHTML = newIsDisabled ? '启用' : '禁用';
        toggleButton.className = `px-6 py-3 ml-4 ${newIsDisabled ? 'bg-green-500' : 'bg-yellow-500'} text-white rounded-lg transition-colors flex-shrink-0`;
        input.disabled = newIsDisabled;
        await saveOptions();
    };
    
    const removeButton = document.createElement('button');
    removeButton.className = 'px-6 py-3 ml-4 bg-red-500 hover:bg-red-600 text-white rounded-lg transition-colors flex-shrink-0';
    removeButton.innerHTML = '删除';
    
    removeButton.onclick = () => {
        if (confirm('确定要删除该网址吗？此操作会立即生效。')) {
            urlItem.classList.add('opacity-0', 'translate-y-2');
            setTimeout(() => {
                urlItem.remove();
                // 如果删除后没有输入框，添加一个新的
                if (urlList.children.length === 0) {
                    addUrlInput('');
                }
                saveOptions();
            }, 300);
        }
    };
    
    urlItem.appendChild(input);
    urlItem.appendChild(toggleButton);
    urlItem.appendChild(removeButton);
    urlList.appendChild(urlItem);

    // 添加动画效果
    requestAnimationFrame(() => {
        urlItem.classList.add('transition-all', 'duration-300');
        requestAnimationFrame(() => {
            urlItem.classList.remove('opacity-0', 'translate-y-2');
        });
    });

    // 添加自动保存
    input.addEventListener('input', () => {
        clearTimeout(input.dataset.saveTimeout);
        input.dataset.saveTimeout = setTimeout(() => {
            saveOptions();
        }, 1000);
    });
}

// 验证 URL 输入
function validateUrlInput(input, matchType) {
    input.setCustomValidity('');
    
    if (!input.value) {
        input.setCustomValidity('请输入 URL');
        return false;
    }

    try {
        switch (matchType) {
            case 'exact':
                try {
                    new URL(input.value);
                } catch (e) {
                    input.setCustomValidity('请输入有效的 URL');
                    return false;
                }
                break;
            
            case 'wildcard':
                const wildcardPattern = input.value.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*');
                new RegExp(`^${wildcardPattern}$`);
                break;
            
            case 'regex':
                new RegExp(input.value);
                break;
        }
        return true;
    } catch (e) {
        input.setCustomValidity('无效的匹配模式');
        return false;
    }
}

// 删除所有保存的表单数据
function clearAllData() {
    if (confirm('确定要删除所有已保存的表单数据和网址配置吗？此操作无法撤销！')) {
        // 再次确认
        if (confirm('此操作将删除：\n1. 所有保存的表单数据\n2. 所有添加的网址配置\n\n确定要继续吗？')) {
            // 同时清除 local 和 sync 存储
            Promise.all([
                chrome.storage.local.clear(),
                chrome.storage.sync.set({ 
                    enabledUrls: [], 
                    disabledUrls: [],
                    enableLogging: true  // 保持默认日志设置
                })
            ]).then(() => {
                // 重新加载网址列表
                loadOptions();
                
                const status = document.getElementById('status');
                status.textContent = '所有数据已清除！';
                status.classList.remove('hidden', 'bg-green-500');
                status.classList.add('bg-yellow-500');
                
                // 显示状态提示，带动画效果
                requestAnimationFrame(() => {
                    status.style.transition = 'all 0.3s ease';
                    status.style.transform = 'translateY(0)';
                    status.style.opacity = '1';
                    
                    setTimeout(() => {
                        status.style.transform = 'translateY(100%)';
                        status.style.opacity = '0';
                        setTimeout(() => {
                            status.classList.add('hidden');
                        }, 300);
                    }, 2000);
                });
            }).catch(error => {
                console.error('清除数据失败:', error);
                showStatus('清除数据失败，请重试！', 'error');
            });
        }
    }
}

// 状态提示函数
function showStatus(message, type) {
    const status = document.getElementById('status');
    status.textContent = message;
    status.classList.remove('hidden', 'bg-green-500', 'bg-yellow-500');
    status.classList.add(type === 'success' ? 'bg-green-500' : 'bg-yellow-500');
    status.style.transform = 'translateX(-50%) translateY(0)';
    status.style.opacity = '1';
    status.style.transition = 'transform 0.3s ease-out, opacity 0.3s ease-out';

    setTimeout(() => {
        status.style.transform = 'translateX(-50%) translateY(100%)';
        status.style.opacity = '0';
    }, 3000);
}

// 导出数据
async function exportData() {
    try {
        // 获取所有存储的数据
        const [localData, syncData] = await Promise.all([
            chrome.storage.local.get(null),
            chrome.storage.sync.get(null)
        ]);

        const exportData = {
            version: '1.0',
            exportDate: new Date().toISOString(),
            localData,
            syncData
        };

        // 创建 Blob 对象
        const blob = new Blob([JSON.stringify(exportData, null, 2)], {
            type: 'application/json'
        });

        // 创建下载链接
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `form-data-backup-${new Date().toISOString().slice(0, 10)}.json`;
        
        // 触发下载
        document.body.appendChild(a);
        a.click();
        
        // 清理
        setTimeout(() => {
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }, 0);

        showStatus('数据导出成功！', 'success');
    } catch (error) {
        console.error('导出数据失败:', error);
        showStatus('导出失败，请重试！', 'error');
    }
}

// 导入数据
async function importData() {
    const fileInput = document.getElementById('importFile');
    if (!fileInput.files.length) {
        fileInput.click();
        return;
    }

    try {
        const file = fileInput.files[0];
        const text = await file.text();
        const importedData = JSON.parse(text);

        // 验证数据格式
        if (!importedData.version || !importedData.localData || !importedData.syncData) {
            throw new Error('无效的备份文件格式');
        }

        if (!confirm('导入数据将覆盖当前的所有设置和保存的表单数据，是否继续？')) {
            return;
        }

        // 清除现有数据
        await Promise.all([
            chrome.storage.local.clear(),
            chrome.storage.sync.clear()
        ]);

        // 导入新数据
        await Promise.all([
            chrome.storage.local.set(importedData.localData),
            chrome.storage.sync.set(importedData.syncData)
        ]);

        showStatus('数据导入成功！', 'success');
        
        // 重新加载选项页面
        setTimeout(() => {
            location.reload();
        }, 1500);
    } catch (error) {
        console.error('导入数据失败:', error);
        showStatus('导入失败，请确保文件格式正确！', 'error');
    } finally {
        // 清除文件输入
        fileInput.value = '';
    }
}

// 数据集管理器
const datasetManager = {
    datasets: [],
    groupedDatasets: {},    // 初始化数据集管理器
    async init() {
        await this.loadDatasets();
        this.validateAndCleanDatasets();
        this.groupDatasetsByUrl();
        await this.renderDatasets();
    },    // 从 storage 加载数据集
    async loadDatasets() {
        const result = await chrome.storage.sync.get('datasets');
        // 如果是对象，将其转换为数组
        if (result.datasets && typeof result.datasets === 'object' && !Array.isArray(result.datasets)) {
            this.datasets = Object.values(result.datasets);
        } else {
            // 如果不是对象或是空值，则使用空数组
            this.datasets = Array.isArray(result.datasets) ? result.datasets : [];
        }
        return this.datasets;
    },

    // 按照 URL 对数据集进行分组
    groupDatasetsByUrl() {
        this.groupedDatasets = {};
        console.log('分组数据集:', this.datasets);

        this.datasets.forEach(dataset => {
            if (dataset && typeof dataset === 'object') {
                const url = dataset.url || '未分类';
                if (!this.groupedDatasets[url]) {
                    this.groupedDatasets[url] = [];
                }
                this.groupedDatasets[url].push(dataset);
            }
        });
    },

    // 渲染数据集列表
    async renderDatasets() {
        const datasetList = document.getElementById('datasetList');
        if (!datasetList) return;

        // 清空现有内容
        datasetList.innerHTML = '';

        // // 添加统计面板
        // const statsPanel = document.createElement('div');
        // statsPanel.className = 'bg-blue-50 p-4 mb-4 rounded-lg';
        // statsPanel.innerHTML = `
        //     <div class="text-lg font-semibold mb-2">数据集统计</div>
        //     <div class="grid grid-cols-3 gap-4">
        //         <div>
        //             <span class="text-gray-600">总数据集:</span>
        //             <span class="text-blue-600 font-bold">${this.datasets.length}</span>
        //         </div>
        //         <div>
        //             <span class="text-gray-600">URL分组数:</span>
        //             <span class="text-blue-600 font-bold">${Object.keys(this.groupedDatasets).length}</span>
        //         </div>
        //         <div>
        //             <span class="text-gray-600">活跃数据集:</span>
        //             <span class="text-blue-600 font-bold">${this.datasets.filter(d => !d.disabled).length}</span>
        //         </div>
        //     </div>
        // `;
        // datasetList.appendChild(statsPanel);

        // 添加全局操作按钮
        const globalControls = document.createElement('div');
        globalControls.className = 'flex justify-between items-center mb-4';
        globalControls.innerHTML = `
            <div class="space-x-2">
                <button id="expandAllBtn" class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">
                    展开全部
                </button>
                <button id="collapseAllBtn" class="px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600">
                    折叠全部
                </button>
                <input type="text" id="datasetSearch" placeholder="搜索数据集..." 
                    class="px-3 py-2 border rounded focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
        `;
        datasetList.appendChild(globalControls);

        // 为每个URL创建一个分组
        Object.entries(this.groupedDatasets).forEach(([url, datasets]) => {
            const groupDiv = document.createElement('div');
            groupDiv.className = 'mb-6 border rounded-lg overflow-hidden';
            
            // 创建分组头部
            const headerDiv = document.createElement('div');
            headerDiv.className = 'bg-gray-100 p-4 flex justify-between items-center cursor-pointer space-x-2';
            headerDiv.style.justifyContent = 'space-between';
            headerDiv.innerHTML = `
                <div class="flex items-center space-x-2">
                    <span class="text-lg font-semibold">${url.length > 50 ? url.substring(0, 50) + "..." : url}</span>
                </div>
                <button class="toggle-group bg-gray-100">
                    <i data-lucide="arrow-down-from-line"></i>
                </button>
            `;

            // 创建数据集容器
            const datasetsDiv = document.createElement('div');
            datasetsDiv.className = 'dataset-group p-4';
            
            // 添加每个数据集
            datasets.forEach(dataset => {
                const datasetDiv = document.createElement('div');
                datasetDiv.className = `dataset-item mb-4 p-4 ${dataset.disabled ? 'bg-gray-100' : 'bg-white'} rounded-lg shadow-sm border`;
                datasetDiv.innerHTML = `
                    <div class="flex justify-between items-start">
                        <div class="flex-1">
                            <div class="flex items-center space-x-2" style='display: flex;align-items: center;'>
                                <span class="text-lg font-medium">${dataset.name}</span>
                                <span class="text-sm text-gray-500">
                                    ${new Date(dataset.createTime).toLocaleString()}
                                </span>
                            </div>
                            <div class="text-sm text-gray-600 mt-1">
                                URL: ${dataset.url.length > 50 ? dataset.url.substring(0, 50) + "..." : dataset.url}
                            </div>
                        </div>
                        <div class="flex space-x-2">
                            <button class="preview-btn px-3 py-1 text-sm text-blue-700 rounded bg-gray-200"
                                data-id="${dataset.createTime}">
                                <i data-lucide='eye'></i>
                            </button>
                            <button class="toggle-btn px-3 py-1 text-sm ${dataset.disabled ? 'text-green-700' : 'text-yellow-700'} rounded bg-gray-200"
                                data-id="${dataset.createTime}">
                                ${dataset.disabled ? '<i data-lucide="ban"></i>' : '<i data-lucide="circle-dot"></i>'}
                            </button>
                            <button class="delete-btn px-3 py-1 text-sm text-red-700 rounded bg-gray-200"
                                data-id="${dataset.createTime}">
                                <i data-lucide="trash-2"></i>
                            </button>
                        </div>
                    </div>
                `;
                datasetsDiv.appendChild(datasetDiv);
            });

            groupDiv.appendChild(headerDiv);
            groupDiv.appendChild(datasetsDiv);
            datasetList.appendChild(groupDiv);

            // 添加分组展开/折叠事件
            headerDiv.addEventListener('click', () => {
                const groupContent = headerDiv.nextElementSibling;
                const toggleBtn = headerDiv.querySelector('.toggle-group');
                
                if (groupContent.style.display === 'none') {
                    groupContent.style.display = 'block';
                    toggleBtn.style.transform = 'rotate(0deg)';
                } else {
                    groupContent.style.display = 'none';
                    toggleBtn.style.transform = 'rotate(-90deg)';
                }
            });
            lucide.createIcons();
        });

        // 添加事件监听
        this.addEventListeners();
    },

    // 添加事件监听器
    addEventListeners() {
        // 展开全部按钮
        document.getElementById('expandAllBtn')?.addEventListener('click', () => {
            document.querySelectorAll('.dataset-group').forEach(group => {
                group.style.display = 'block';
                group.previousElementSibling.querySelector('.toggle-group').style.transform = 'rotate(0deg)';
            });
        });

        // 折叠全部按钮
        document.getElementById('collapseAllBtn')?.addEventListener('click', () => {
            document.querySelectorAll('.dataset-group').forEach(group => {
                group.style.display = 'none';
                group.previousElementSibling.querySelector('.toggle-group').style.transform = 'rotate(-90deg)';
            });
        });

        // 数据集搜索
        document.getElementById('datasetSearch')?.addEventListener('input', (e) => {
            const searchTerm = e.target.value.toLowerCase();
            document.querySelectorAll('.dataset-item').forEach(item => {
                const text = item.textContent.toLowerCase();
                item.style.display = text.includes(searchTerm) ? 'block' : 'none';
            });
        });        // 为所有预览按钮添加事件
        document.querySelectorAll('.preview-btn').forEach(btn => {
            btn.addEventListener('click', async () => {
                const dataset = this.datasets.find(d => d.createTime === parseInt(btn.dataset.id));
                if (dataset) {
                    const previewContent = JSON.stringify(dataset.data, null, 2);
                    const datasetItem = btn.closest('.dataset-item');
                    
                    // 移除其他所有预览面板
                    document.querySelectorAll('.preview-panel').forEach(panel => panel.remove());
                    
                    // 如果已经有预览面板，则移除它
                    const existingPreview = datasetItem.nextElementSibling;
                    if (existingPreview?.classList.contains('preview-panel')) {
                        existingPreview.remove();
                        return;
                    }
                    
                    // 创建预览面板
                    const previewPanel = document.createElement('div');
                    previewPanel.className = 'preview-panel mb-4 mt-2 bg-white rounded-lg shadow-sm overflow-hidden transition-all border';
                    previewPanel.style.maxHeight = '0';
                    previewPanel.innerHTML = `
                        <div class="border-t border-gray-100">
                            <div class="p-4">
                                <div class="flex justify-between items-center mb-2" style="justify-content: space-between;">
                                    <h3 class="text-lg font-semibold text-gray-700">数据预览: ${dataset.name}</h3>
                                    <button class="close-preview hover:text-gray-700">
                                        <i data-lucide="eye-off"></i>
                                    </button>
                                </div>
                                <pre class="bg-gray-50 p-4 rounded overflow-auto text-sm" style="max-height: 300px">${previewContent}</pre>
                            </div>
                        </div>
                    `;
                    
                    // 插入预览面板
                    datasetItem.insertAdjacentElement('afterend', previewPanel);
                    
                    // 添加动画效果
                    requestAnimationFrame(() => {
                        previewPanel.style.maxHeight = previewPanel.scrollHeight + 'px';
                    });
                    
                    // 添加关闭按钮事件
                    previewPanel.querySelector('.close-preview').addEventListener('click', () => {
                        previewPanel.style.maxHeight = '0';
                        setTimeout(() => previewPanel.remove(), 300);
                    });

                    lucide.createIcons();
                }
            });
        });

        // 为所有启用/禁用按钮添加事件
        document.querySelectorAll('.toggle-btn').forEach(btn => {
            btn.addEventListener('click', async () => {
                const dataset = this.datasets.find(d => d.createTime === parseInt(btn.dataset.id));
                if (dataset) {
                    dataset.disabled = !dataset.disabled;
                    await this.saveDatasets();
                    await this.renderDatasets();
                }
            });
        });

        // 为所有编辑按钮添加事件
        document.querySelectorAll('.edit-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                alert('编辑功能开发中...');
            });
        });

        // 为所有删除按钮添加事件
        document.querySelectorAll('.delete-btn').forEach(btn => {
            btn.addEventListener('click', async () => {
                if (confirm('确定要删除这个数据集吗？此操作不可恢复。')) {
                    const index = this.datasets.findIndex(d => d.createTime === parseInt(btn.dataset.id));
                    if (index !== -1) {
                        this.datasets.splice(index, 1);
                        await this.saveDatasets();
                        await this.renderDatasets();
                    }
                }
            });
        });
    },

    // 保存数据集到 storage
    async saveDatasets() {
        await chrome.storage.sync.set({ datasets: this.datasets });
    },

    // 验证并清理数据集
    validateAndCleanDatasets() {
        if (!Array.isArray(this.datasets)) {
            console.error('数据集不是数组，重置为空数组');
            this.datasets = [];
            return;
        }

        this.datasets = this.datasets.filter(dataset => {
            // 验证数据集格式
            if (!dataset || typeof dataset !== 'object') {
                console.warn('移除无效的数据集:', dataset);
                return false;
            }

            // 验证必要字段
            const requiredFields = ['name', 'url', 'createTime', 'data'];
            const hasAllFields = requiredFields.every(field => {
                const hasField = field in dataset;
                if (!hasField) {
                    console.warn(`数据集缺少必要字段 ${field}:`, dataset);
                }
                return hasField;
            });

            if (!hasAllFields) {
                return false;
            }

            // 确保 createTime 是数字
            if (typeof dataset.createTime !== 'number') {
                try {
                    dataset.createTime = parseInt(dataset.createTime);
                    if (isNaN(dataset.createTime)) {
                        console.warn('无效的 createTime:', dataset);
                        return false;
                    }
                } catch (e) {
                    console.warn('无法解析 createTime:', dataset);
                    return false;
                }
            }

            // 确保 data 是对象
            if (typeof dataset.data !== 'object' || dataset.data === null) {
                console.warn('无效的 data 字段:', dataset);
                return false;
            }

            return true;
        });

        // 按创建时间排序
        this.datasets.sort((a, b) => b.createTime - a.createTime);
    },
};

// 保存数据集
async function saveDataset(url, name, data) {
    try {
        const { datasets = {} } = await chrome.storage.local.get('datasets');
        if (!datasets[url]) {
            datasets[url] = {};
        }
        datasets[url][name] = {
            timestamp: Date.now(),
            data: data
        };
        await chrome.storage.local.set({ datasets });
        showStatus(await getMessage('datasetSaved'), 'success');
    } catch (error) {
        console.error('保存数据集失败:', error);
        showStatus(await getMessage('errorSavingDataset'), 'error');
    }
}

// 清除数据集
async function clearDataset(url, name) {
    try {
        const { datasets = {} } = await chrome.storage.local.get('datasets');
        if (datasets[url] && datasets[url][name]) {
            delete datasets[url][name];
            if (Object.keys(datasets[url]).length === 0) {
                delete datasets[url];
            }
            await chrome.storage.local.set({ datasets });
            showStatus(await getMessage('datasetCleared'), 'success');
        }
    } catch (error) {
        console.error('清除数据集失败:', error);
        showStatus(await getMessage('errorClearingDataset'), 'error');
    }
}

// 导出数据集
async function exportDataset(url, name) {
    try {
        const { datasets = {} } = await chrome.storage.local.get('datasets');
        if (!datasets[url] || !datasets[url][name]) {
            throw new Error('数据集不存在');
        }

        const dataset = datasets[url][name];
        const blob = new Blob([JSON.stringify(dataset.data, null, 2)], {
            type: 'application/json'
        });

        // 创建下载链接
        const downloadUrl = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = downloadUrl;
        a.download = `${name}-${new Date().toISOString().slice(0, 10)}.json`;
        
        // 触发下载
        document.body.appendChild(a);
        a.click();
        
        // 清理
        setTimeout(() => {
            document.body.removeChild(a);
            URL.revokeObjectURL(downloadUrl);
        }, 0);

        showStatus('数据集导出成功！', 'success');
    } catch (error) {
        console.error('导出数据集失败:', error);
        showStatus('导出数据集失败，请重试！', 'error');
    }
}

// 导入数据集
async function importDataset(file) {
    try {
        const text = await file.text();
        const importedData = JSON.parse(text);

        // 验证数据集格式
        if (!importedData.timestamp || !importedData.data) {
            throw new Error('无效的数据集文件格式');
        }

        const url = prompt('请输入数据集对应的网址前缀（例如：/video/）：');
        if (!url) {
            return;
        }

        // 保存数据集
        await saveDataset(url, file.name, importedData.data);
        
        // 重新加载数据集列表
        datasetManager.loadDatasets();
    } catch (error) {
        console.error('导入数据集失败:', error);
        showStatus('导入数据集失败，请确保文件格式正确！', 'error');
    }
}

// 监听消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.action === 'optionsPageUpdate') {
        // 重新加载选项
        loadOptions();
        
        // 显示更新提示
        showStatus('设置已更新', 'success');
    }
});

// 轮询检查语言设置
let currentLanguage = null;

async function pollLanguageSettings() {
    try {
        const { language = 'zh_CN' } = await chrome.storage.sync.get('language');
        
        // 如果语言设置发生变化
        if (currentLanguage !== null) {
            console.log('检测到语言变化:', currentLanguage, '->', language);
            // 重新加载页面以应用新语言
            updateI18nText();
        }
        
        currentLanguage = language;
    } catch (error) {
        console.error('检查语言设置失败:', error);
    }
}

// 事件监听器
document.addEventListener('DOMContentLoaded', () => {
    loadOptions();
    loadLanguageSettings(); // 加载初始语言设置
    
    // 启动语言设置轮询
    setInterval(pollLanguageSettings, 1000); // 每秒检查一次
    
    // 加载所有需要国际化的文本
    document.querySelectorAll('[data-i18n]').forEach(element => {
        const key = element.getAttribute('data-i18n');
        element.textContent = chrome.i18n.getMessage(key);
    });

    // 添加网址逻辑
    const addUrlButton = document.getElementById('addUrl');
    if (addUrlButton) {
        addUrlButton.addEventListener('click', () => {
            addUrlInput('');
        });
    }

    // 修改删除网址逻辑为自动保存并添加确认
    const urlList = document.getElementById('urlList');
    if (urlList) {
        urlList.addEventListener('click', (event) => {
            if (event.target.tagName === 'BUTTON' && event.target.textContent === '删除') {
                if (confirm('确定要删除该网址吗？此操作会立即生效。')) {
                    event.target.parentElement.remove();
                    saveOptions(); // 自动保存
                }
            }
        });

        // 添加网址输入框的内容变化监听
        urlList.addEventListener('input', (event) => {
            if (event.target.tagName === 'INPUT' && event.target.type === 'text') {
                // 使用防抖进行自动保存
                clearTimeout(event.target.dataset.saveTimeout);
                event.target.dataset.saveTimeout = setTimeout(() => {
                    saveOptions();
                }, 1000); // 1秒后自动保存
            }
        });
    }

    // 添加日志设置的即时保存功能
    const enableLoggingCheckbox = document.getElementById('enableLogging');
    if (enableLoggingCheckbox) {
        enableLoggingCheckbox.addEventListener('change', async (event) => {
            const enableLogging = event.target.checked;
            try {
                await chrome.storage.sync.set({ enableLogging });
                showStatus('日志设置已保存', 'success');
            } catch (error) {
                showStatus('保存设置失败', 'error');
                console.error('保存日志设置失败:', error);
                // 恢复复选框状态
                event.target.checked = !enableLogging;
            }
        });
    }

    // 添加删除所有数据按钮事件监听
    const clearAllDataButton = document.getElementById('clearAllData');
    if (clearAllDataButton) {
        clearAllDataButton.addEventListener('click', clearAllData);
    }

    // 添加导出/导入按钮事件监听
    document.getElementById('exportData')?.addEventListener('click', exportData);
    document.getElementById('importData')?.addEventListener('click', () => {
        const fileInput = document.getElementById('importFile');
        if (fileInput.files.length) {
            importData();
        } else {
            fileInput.click();
        }
    });
    
    document.getElementById('importFile')?.addEventListener('change', (e) => {
        if (e.target.files.length) {
            importData();
        }
    });

    // 标签页切换功能
    const tabButtons = document.querySelectorAll('.tab-button');
    const tabContents = document.querySelectorAll('.tab-content');

    function switchTab(tabId) {
        // 移除所有激活状态
        tabButtons.forEach(button => button.classList.remove('active'));
        tabContents.forEach(content => content.classList.remove('active'));

        // 设置当前标签为激活状态
        const activeButton = document.querySelector(`[data-tab="${tabId}"]`);
        const activeContent = document.getElementById(tabId);
        
        if (activeButton && activeContent) {
            activeButton.classList.add('active');
            activeContent.classList.add('active');
        }
    }

    // 为每个标签按钮添加点击事件
    tabButtons.forEach(button => {
        button.addEventListener('click', () => {
            const tabId = button.getAttribute('data-tab');
            switchTab(tabId);
        });
    });

    // 初始化数据集管理器
    datasetManager.init();
});

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', async () => {
    // 加载语言设置
    await loadLanguageSettings();
    
    // 加载URL列表设置
    loadOptions();
    
    // 初始化数据集管理器
    await datasetManager.init();
    
    // 更新页面的所有i18n文本
    await updateI18nText();
    
    // 为添加URL按钮添加事件监听
    document.getElementById('addUrl')?.addEventListener('click', () => {
        addUrlInput('');
    });
    
    // 为语言选择器添加事件监听
    document.getElementById('languageSelect')?.addEventListener('change', async (event) => {
        await saveLanguageSettings(event.target.value);
    });
});

// 监听语言更改消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.action === 'updateLanguage' && !window.location.pathname.endsWith('options.html')) {
        // 重新加载所有国际化文本
        updateI18nText();
        sendResponse({ success: true });
    }
});
